package com.vancouver.knows.ui.fragment.my;

import java.io.File;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.FileUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.BuildConfig;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.my.MyArticleActivity;
import com.vancouver.knows.ui.activity.my.MyAtcommentActivity;
import com.vancouver.knows.ui.activity.my.MyCommentActivity;
import com.vancouver.knows.ui.activity.my.MyFeedbackAboutProcotolActivity;
import com.vancouver.knows.ui.activity.my.MyFollowedActivity;
import com.vancouver.knows.ui.activity.my.MyPointsActivity;
import com.vancouver.knows.ui.activity.my.MyPointsWebViewActivity;
import com.vancouver.knows.ui.activity.my.SelectWindow;
import com.vancouver.knows.ui.activity.set.MessageRemindActivity;
import com.vancouver.knows.ui.base.BaseFragment;
import com.vancouver.knows.ui.common.ListViewForScrollView;
import com.vancouver.knows.ui.fragment.citynews.Crop;
import com.vancouver.knows.ui.fragment.citynews.SelectPicWindow;
import com.vancouver.knows.ui.fragment.my.UserSetListAdapter.ViewValueHand;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;
import com.vancouver.knows.util.PhoConstants;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.task.mark.QueryUserInfoTaskMark;
import com.vancouver.knows.business.task.mark.UserUploadImageTaskMark;

public class UserFragment extends BaseFragment implements OnClickListener, IResultReceiver {

	@Bind(R.id.scrollView)
	ScrollView mScrollView;
	@Bind(R.id.toobarTitle)
	TextView mToobarTitle;
	@Bind(R.id.img)
	ImageView mUserImg;
	@Bind(R.id.text)
	TextView mUserName;
	@Bind(R.id.atcomment_text)
	TextView mAatcommentxt;
	@Bind(R.id.article_number)
	TextView articleNumber;
	@Bind(R.id.comment_number)
	TextView commentNumber;
	@Bind(R.id.atcomment_number)
	TextView atcommentNumber;
	@Bind(R.id.listview)
	ListViewForScrollView mListView;
	@Bind(R.id.version)
	TextView mVersionName;

	private final int MESSAGE_REMIND = 0;
	private final int CLEAR_CACHE = 1;
	private final int FEEDBACK = 2;
	private final int ABOUT_US = 3;
	private final int USER_PROTOCAL = 4;
	private final int LOGIN_OR_OUT_SET = 5;

	private LayoutInflater mInflater;
	private UserSetListAdapter mUserAdapter;
	private SelectPicWindow selectPicWindow;
	private SelectWindow loginOrQuitWindows, cacheWindows;
	private BSharedPrefManager sharePrefManager;
	private BusinessModule bModule;
	private String[] mAttrTitles;
	private String loginOrQuitSign = "LOGIN_OR_QUIT_WINDOW";
	private String cacheSign = "CACHE_WINDOW";
	private String currentOpenWhich;

	public static UserFragment newInstance() {
		return new UserFragment();
	}

	public int getloginOrOutPos(){
		return LOGIN_OR_OUT_SET;
	}

	@Override
	protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mInflater = inflater;
		return inflater.inflate(R.layout.activity_my, container, false);
	}

	@Override
	protected void bindView(View rootView) {
		setViews();
		setListeners();
	}

	@Override
	public void onResume() {
		super.onResume();
		queryUserInfo();
		showOrHideUnReadNumber();
		Tracker t = ((MainApplication) getActivity().getApplication()).getTracker(TrackerName.APP_TRACKER);
		t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_MY_FRAGMENT);
		t.send(new HitBuilders.ScreenViewBuilder().build());
	}

	private void queryUserInfo() {
		if (sharePrefManager != null && sharePrefManager.getUserId() != null) {
			QueryUserInfoTaskMark taskMark = bModule.getTaskMarkPool().getQueryUserInfoTaskMark();

			bModule.getServiceWrapper().queryUserInfo(this, taskMark, sharePrefManager.getUserId());
		}
	}

	private void setViews() {
		initBusinessModule();
		sharePrefManager = ((MainApplication) getActivity().getApplicationContext()).getSharedPrefManager();
		mToobarTitle.setText(getActivity().getString(R.string.my_title));
		setUserLoginStatus();
		mAatcommentxt.setText("@" + getActivity().getString(R.string.my_atcomment));
		mUserAdapter = new UserSetListAdapter(getActivity(), mInflater);
		mListView.setDividerHeight(0);
		mListView.setAdapter(mUserAdapter);
		selectPicWindow = new SelectPicWindow(getActivity(), this);

		String versionName = "v" + BuildConfig.VERSION_NAME;
		if (BuildConfig.DEBUG) {
			versionName += " (DEBUG)";
		}
		mVersionName.setText(versionName);
	}

	private void showOrHideUnReadNumber() {
		if (sharePrefManager != null && sharePrefManager.getUserId() != null) {
			if (sharePrefManager.getCloseAllMessage()) {
				// 显示未读图标
				if (sharePrefManager.getMyArticleNewComment()
						&& !sharePrefManager.getTotalUnReadPostComment().equals("0")) {
					articleNumber.setVisibility(View.VISIBLE);
					articleNumber.setText(sharePrefManager.getTotalUnReadPostComment());
				} else {
					articleNumber.setVisibility(View.GONE);
				}

				if (sharePrefManager.getHaveAtCommentMessage()
						&& !sharePrefManager.getTotalUnReadComment().equals("0")) {
					atcommentNumber.setVisibility(View.VISIBLE);
					atcommentNumber.setText(sharePrefManager.getTotalUnReadComment());
				} else {
					atcommentNumber.setVisibility(View.GONE);
				}

				return;
			}
		}

		// 隐藏未读图标
		articleNumber.setVisibility(View.GONE);
		atcommentNumber.setVisibility(View.GONE);
	}

	private void setUserLoginStatus() {
		if (sharePrefManager.getUserId() != null) {
			if (sharePrefManager.getAvatar() != null && sharePrefManager.getAvatar().length() != 0) {
				setUserImg(sharePrefManager.getAvatar());
			} else {
				setDefaultImage();
			}
			mUserName.setText(sharePrefManager.getUserName());
		} else {
			setDefaultImage();
			mUserName.setText(getActivity().getString(R.string.click_login));
		}
	}

	private void setDefaultImage() {
		Picasso.with(getActivity()).load(R.drawable.me_icon_login).transform(new CircleTransform())
				.resizeDimen(R.dimen.addpost_img_size, R.dimen.addpost_img_size).into(mUserImg);
	}

	private boolean getLoginStatus() {
		if (sharePrefManager.getUserId() != null) {
			return true;
		} else {
			startActivity(new Intent(getActivity(), LoginActivity.class));
			return false;
		}
	}

	@OnClick(R.id.img)
	public void onUserImageClick() {
		if (getLoginStatus()) {
			selectPicWindow.show();
		}
	}

	@OnClick(R.id.img_attention)
	public void onAttentionClick() {
		if (getLoginStatus()) {
			Intent intent = new Intent(getActivity(), MyFollowedActivity.class);
			intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_attention));
			startActivity(intent);
		}
	}

	@OnClick(R.id.img_article)
	public void onArticleClick() {
		if (getLoginStatus()) {
			Intent intent = new Intent(getActivity(), MyArticleActivity.class);
			intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_article));
			startActivity(intent);
		}
	}

	@OnClick(R.id.img_comment)
	public void onCommentClick() {
		if (getLoginStatus()) {
			Intent intent = new Intent(getActivity(), MyCommentActivity.class);
			intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_comment));
			startActivity(intent);
		}
	}

	@OnClick(R.id.img_atcomment)
	public void onAtCommentClick() {
		if (getLoginStatus()) {
			Intent intent = new Intent(getActivity(), MyAtcommentActivity.class);
			intent.putExtra("MY_TITLE", "@" + getActivity().getString(R.string.my_comment));
			startActivity(intent);
		}
	}

	@OnClick(R.id.my_points_layout)
	public void onMyPointsClick(){
		if (getLoginStatus()) {
			Intent intent = new Intent(getActivity(), MyPointsActivity.class);
			intent.putExtra("MY_TITLE", getActivity().getString(R.string.my_points));
			startActivity(intent);
		}
	}

	@OnClick(R.id.my_shop_layout)
	public void onMyShopClick() {
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		String pointsShop;
		if (userInfo != null && userInfo.getUserID() != null && userInfo.userPointsDetailsInfo != null) {
			pointsShop = userInfo.userPointsDetailsInfo.getPointsStore();

		}else {
			pointsShop = "https://vancoolver.ca/point_store.html";
		}

		Intent intent = new Intent(getActivity(), MyPointsWebViewActivity.class);
		intent.putExtra("USER_NOTICE", getActivity().getString(R.string.points_shop));
		intent.putExtra("POINT_URL", pointsShop);
		startActivity(intent);
	}

	@Override
	public void subHandleMessage(Message msg) {
		switch (msg.what) {
			case Constants.BUSINESS_STATUS_LOGIN_SUCCESS:
			case Constants.BUSINESS_STATUS_LOGIN_OVERTIME:
				updateUserView();

				break;
		}
	}

	private void updateUserView() {
		showOrHideUnReadNumber();
		setUserLoginStatus();
		if (mUserAdapter != null)
			mUserAdapter.notifyDataSetChanged();
	}

	private void initBusinessModule() {
		Application app = getActivity().getApplication();
		bModule = ((MainApplication) app).getBusinessModule();
	}

	private void clearUserCache() {
		setUserImg();
		((MainApplication) getActivity().getApplication()).clearUserCacheNoGoLogin();
	}

	private void setListeners() {
		mAttrTitles = getActivity().getResources().getStringArray(R.array.my_list_titles);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ViewValueHand hand = (ViewValueHand) view.getTag();
				Intent intent = null;
				switch (position) {
					case MESSAGE_REMIND: {
						if (getLoginStatus()) {
							intent = new Intent(getActivity(), MessageRemindActivity.class);
							intent.putExtra("COMMON_TIPS", getActivity().getString(R.string.message_title));
							startActivity(intent);
						}
					}
					break;
					case LOGIN_OR_OUT_SET:
						if (hand.title.getText().equals(getActivity().getString(R.string.login))) {
							startActivity(new Intent(getActivity(), LoginActivity.class));

						} else {
							loginOrQuitWindows = createWindow(getActivity().getString(R.string.sure_quit), getActivity().getString(R.string.sure));
							loginOrQuitWindows.show();
							currentOpenWhich = loginOrQuitSign;
						}
						break;
					case CLEAR_CACHE: {
						cacheWindows = createWindow(getActivity().getString(R.string.sure_cache),
								getActivity().getString(R.string.cache));
						cacheWindows.show();
						currentOpenWhich = cacheSign;
					}
					break;
					case FEEDBACK: {
						intent = new Intent(getActivity(), MyFeedbackAboutProcotolActivity.class);
						intent.putExtra("USER_NOTICE", mAttrTitles[FEEDBACK]);
						intent.putExtra("PAGE_TYPE", "feedback");
						startActivity(intent);
					}
					break;
					case ABOUT_US: {
						intent = new Intent(getActivity(), MyFeedbackAboutProcotolActivity.class);
						intent.putExtra("USER_NOTICE", mAttrTitles[ABOUT_US]);
						intent.putExtra("PAGE_TYPE", "about_us");
						startActivity(intent);
					}
					break;
					case USER_PROTOCAL: {
						intent = new Intent(getActivity(), MyFeedbackAboutProcotolActivity.class);
						intent.putExtra("USER_NOTICE", mAttrTitles[USER_PROTOCAL]);
						intent.putExtra("PAGE_TYPE", "user_terms");
						startActivity(intent);
					}
					break;
				}

				mUserAdapter.notifyDataSetChanged();
			}
		});

	}

	private SelectWindow createWindow(String tips, String sure) {
		return new SelectWindow(getActivity(), this, tips, sure);
	}

	/*
	 * Resources resources = getResources();//获得res资源对象 Configuration config =
	 * resources.getConfiguration();//获得设置对象 DisplayMetrics dm = resources
	 * .getDisplayMetrics();//获得屏幕参数：主要是分辨率，像素等。 config.locale =
	 * Locale.SIMPLIFIED_CHINESE; //简体中文 resources.updateConfiguration(config,
	 * dm);
	 */

	private void setUserImg() {
		setDefaultImage();
		mUserName.setText(getActivity().getString(R.string.click_login));
		if (mUserAdapter != null)
			mUserAdapter.notifyDataSetChanged();
	}

	private void setUserImg(String imgUrl) {
		Picasso.with(getActivity()).load(imgUrl).transform(new CircleTransform()).centerCrop()
				.resizeDimen(R.dimen.detail_user_followed_size, R.dimen.detail_user_followed_size).into(mUserImg);
	}

	private void setUserImgFromPhoto(File imgFile) {
		Picasso.with(getActivity()).load(imgFile).transform(new CircleTransform()).centerCrop()
				.resizeDimen(R.dimen.detail_user_followed_size, R.dimen.detail_user_followed_size).into(mUserImg);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		String userImageUrl = null;
		if (requestCode == Crop.REQUEST_PICK && resultCode == Activity.RESULT_OK) {
			Uri uri = data.getData();
			String path = AppUtils.createFile(getActivity(), uri, FileUtil.getSdcardStoreDir() + File.separator
					+ PhoConstants.ADD_POST_IMAGE_DIR + System.currentTimeMillis() + ".jpg");
			if (!StringUtil.isEmptyString(path)) {
				setUserImgFromPhoto(new File(path));
				userImageUrl = path;
			}

		} else if (requestCode == Crop.REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
			setUserImgFromPhoto(new File(localFilePath));
			userImageUrl = localFilePath;
		}

		if ((requestCode == Crop.REQUEST_PICK || requestCode == Crop.REQUEST_CAMERA) && resultCode == Activity.RESULT_OK) {
			if (userImageUrl != null && userImageUrl.length() > 0) {
				UserUploadImageTaskMark taskMark = bModule.getTaskMarkPool().getUserUploadImageTaskMark();
				bModule.getServiceWrapper().userUploadImage(this, taskMark, sharePrefManager.getUserId(), userImageUrl);
			}
		}
	}

	@Override
	public void onDestroy() {
		destroyEnvironment();
		super.onDestroy();
	}

	private void destroyEnvironment() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
			FileUtil.delAllChildrenFiles(imgDir);
		}
	}

	private String localFilePath;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/* 从相机获取头像 */
			case R.id.btn_take_photo:
				selectPicWindow.dismiss();
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
					File dir = new File(imgDir);
					if (!dir.exists()) {
						dir.mkdirs();
					}

					localFilePath = imgDir + System.currentTimeMillis() + ".jpg";
					Crop.cameraImage(this, Crop.REQUEST_CAMERA, Uri.fromFile(new File(localFilePath)));

				} else {
					Toast.makeText(getActivity(), R.string.check_sdcard, Toast.LENGTH_SHORT).show();
				}

				break;

		/* 从相册获取图片 */
			case R.id.btn_pick_photo:
				String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
				File dir = new File(imgDir);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				selectPicWindow.dismiss();
				Crop.pickImage(this, Crop.REQUEST_PICK);

				break;
			case R.id.sure:
				if (!StringUtil.isEmptyString(currentOpenWhich)) {
					if (currentOpenWhich.equals(loginOrQuitSign)) {
						loginOrQuitWindows.dismiss();
						clearUserCache();
						showOrHideUnReadNumber();
					} else if (currentOpenWhich.equals(cacheSign)) {
						cacheWindows.dismiss();
						AppUtils.clearImageDiskCache(getActivity());
						Toast.makeText(getActivity(), getActivity().getString(R.string.cached), Toast.LENGTH_SHORT).show();

					}
				}
				break;
		}
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (exception != null && !exception.getExMessage().equals("")) {
			Toast.makeText(getActivity(), exception.getExMessage(), Toast.LENGTH_LONG).show();
			return;
		}

		if (sharePrefManager != null) {
			if (taskMark instanceof QueryUserInfoTaskMark) {
				showOrHideUnReadNumber();
			} else {
				if (sharePrefManager.getAvatar() == null && sharePrefManager.getAvatar().length() == 0) {
					setDefaultImage();
				} else {
					setUserImg(sharePrefManager.getAvatar());
				}
			}
		}
	}

	public void scrollUp() {
		if (mScrollView != null) {
			mScrollView.scrollTo(0, 0);
		}
	}

}
